package com.example.testdemo.demos.web.Service.Impl;



import com.alibaba.fastjson2.JSON;
import com.example.testdemo.demos.web.Config.JwtInfo;
import com.example.testdemo.demos.web.Config.Result;
import com.example.testdemo.demos.web.Config.ResultEnum;
import com.example.testdemo.demos.web.Dao.GoodsDao;
import com.example.testdemo.demos.web.Dao.MerchantDao;
import com.example.testdemo.demos.web.Dao.OrderDao;
import com.example.testdemo.demos.web.Dao.OrderDetailsDao;
import com.example.testdemo.demos.web.Dto.CreateOrderDTO;
import com.example.testdemo.demos.web.Entity.Goods;
import com.example.testdemo.demos.web.Entity.Merchant;
import com.example.testdemo.demos.web.Entity.Order;
import com.example.testdemo.demos.web.Entity.OrderDetails;
import com.example.testdemo.demos.web.Service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.testdemo.demos.web.Tool.SerialNumberTool.OrderNumber;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private GoodsDao goodsDao;

    @Resource
    private MerchantDao merchantDao;

    @Resource
    private OrderDetailsDao orderDetailsDao;

    @Resource //它定义了事务管理器的基本功能，如开始、提交、回滚事务等。
    PlatformTransactionManager platformTransactionManager;
    @Resource //它定义了事务的属性，如事务的传播行为、隔离级别、超时时间等。
    TransactionDefinition transactionDefinition;


    /**
     * 创建订单
     */
    @Override
    public Result addOrder(CreateOrderDTO dto, JwtInfo jwtInfo){
        TransactionStatus transactionStatus=platformTransactionManager.getTransaction(transactionDefinition);
        Result result = new Result();
        Order order =new Order();
        try {
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("订单创建成功");
            Double totalPrice = 0.00;
            List<Goods> goodsList = goodsDao.selectBatchIds(dto.getGoodsList().stream().map(Goods::getGoodsId).collect(Collectors.toList()));
            for (Goods goods : goodsList) {
                totalPrice += goods.getPrice();
            }
            //创建订单号
            String orderId = OrderNumber(goodsList.size(),totalPrice);
            order.setOrderId(orderId);
            //设置用户id
            order.setUserId(jwtInfo.getUserId());
            //商品名称默认取商品的第一个
            order.setOrderName(goodsList.get(0).getGoodsName());
            //商品总价格
            order.setTotalPrice(totalPrice);
            //实付价格 优惠信息还未确定
            order.setPaidPrice(totalPrice);
            //购买子订单数量
            order.setQuantity(goodsList.size());
            order.setOrderTime(new Date());
            //支付状态
            order.setPayStatus("W");
            //支付状态名称
            order.setPayStatusName("未支付");
            //订单状态
            order.setOrderStatus("D");
            //订单状态名称
            order.setOrderStatusName("待支付");
            //订单备注
            order.setOrderRemark(dto.getOrderRemar());
            int res =orderDao.insert(order);
            if (res==1){
                for (Goods item : goodsList) {
                    OrderDetails orderDetails=(JSON.parseObject(JSON.toJSONString(item), OrderDetails.class));
                    //设置订单id
                    orderDetails.setOrderId(orderId);
                    //设置用户id
                    orderDetails.setUserId(jwtInfo.getUserId());
                    //商品数量
                    orderDetails.setQuantity(1);
                    //物流状态  待出单
                    orderDetails.setLogisticsStatus("DCD");
                    //订单状态 待支付
                    orderDetails.setOrderStatus("D");
                    //签收状态 待签收
                    orderDetails.setSignStatus("D");
                    //订单备注
                    orderDetails.setOrderRemaker(dto.getOrderRemar());
                    //商品价格
                    orderDetails.setPrice(item.getPrice());
                    //查询商家信息
                    Merchant merchant = merchantDao.selectById(item.getMerchantId());
                    if (!(merchant==null)){
                        //商家名称
                        orderDetails.setMerchantName(merchant.getStoreName());
                        //商家图片
                        orderDetails.setStoreImage(merchant.getStoreImage());
                        int res2 = orderDetailsDao.insert(orderDetails);
                        if (res2==1){
                            if (item.getTotalStock()>=item.getSold()){
                                Goods goods =new Goods();
                                goods.setSold(item.getSold()+1);
                                goods.setGoodsId(item.getGoodsId());
                                goodsDao.updateById(goods);
                            } else{
                                platformTransactionManager.rollback(transactionStatus);
                                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                                result.setMsg("产品已售空！");
                                break;
                            }
                        }else {
                            platformTransactionManager.rollback(transactionStatus);
                            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                            result.setMsg("订单明细创建错误！");
                            break;
                        }
                    }else {
                        platformTransactionManager.rollback(transactionStatus);
                        result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                        result.setMsg("商户信息错误！");
                        break;
                    }
                }
                platformTransactionManager.commit(transactionStatus);
            }else {
                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                result.setMsg("订单创建失败！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(e.getCause());
        }
        return result;
    }


}
